package com.cqw.order.service;

import com.alibaba.fastjson.JSON;
import com.cqw.common.PageableEntitiesConverter;
import com.cqw.domain.SysUser;
import com.cqw.exception.CommonException;
import com.cqw.order.domain.Spu;
import com.cqw.order.mapper.SpuMapper;
import com.cqw.utils.SecurityUtils;
import com.cqw.vo.order.SpuReq;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Author: caoqingwen
 * @CreateTime: 2021-07-12 17:36
 * @Description:
 */
@Service
@Slf4j
public class SpuService {


    @Autowired
    private SpuMapper spuMapper;


    /**
     * 分页查询SPU
     *
     * @param pageIndex
     * @param pageSize
     * @return
     */
    public List<Spu> getSpuPage(int pageIndex, int pageSize) {
        PageHelper.startPage(pageIndex, pageSize, "create_time desc");
        Spu spu = new Spu();
        spu.setShopId(1L);
        List<Spu> spuList = spuMapper.selectBySelective(spu);
        return PageableEntitiesConverter.toPageEntities(spuList);
    }


    /**
     * 新增SPU
     *
     * @param spuReq
     * @return
     */
    @Transactional(transactionManager = "oneTransactionManager", rollbackFor = Exception.class)
    public Spu createSpu(SpuReq spuReq) {
        log.info("新增SPU参数：{}", JSON.toJSONString(spuReq));
        int count = spuMapper.selectCountByName(spuReq.getShopId(), spuReq.getSpuName());
        if (count > 0) {
            throw new CommonException("商品名称已存在");
        }

        SysUser loginUser = SecurityUtils.getLoginUser();
        spuReq.setShopId(loginUser.getShopId());
        Spu insertParam = new Spu(spuReq);
        spuMapper.insertSelective(insertParam);
        log.info("新增SPU返回：{}", JSON.toJSONString(insertParam));
        return insertParam;
    }


    /**
     * 修改spu
     *
     * @param spuReq
     * @return
     */
    @Transactional(transactionManager = "oneTransactionManager", rollbackFor = Exception.class)
    public Spu updateSpu(SpuReq spuReq) {
        log.info("修改SPU参数：{}", JSON.toJSONString(spuReq));
        //todo 修改SPU暂时只能修改名称
        Spu updateParam = new Spu(spuReq);
        updateParam.setCreateTime(null);
        spuMapper.updateByPrimaryKeySelective(updateParam);
        return updateParam;
    }


}
